<template>
  <el-tabs v-model="activeTab" class="demo-tabs" @edit="handleTabsEdit">
    <el-tab-pane
      v-for="item in tabs"
      :key="item.fullpath"
      :label="item.title"
      :name="item.fullpath"
      :closable="item.title === 'Home' ? false : true"
    >
    </el-tab-pane>
  </el-tabs>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { TabPaneName } from "element-plus";

type TabInfo = {
  path: string;
  fullpath: string;
  name: string;
  title?: string;
  meta?: any;
};

const route = useRoute();
const router = useRouter();

const tabs = ref<TabInfo[]>([
  {
    path: "/",
    fullpath: "/",
    name: "Home",
    title: "Home",
    meta: { title: "Home", closable: false }
  }
]);
const activeTab = ref("/");

watch(
  () => route.fullPath,
  newPath => {
    const foundTab = tabs.value.find(tab => tab.fullpath === newPath);
    if (foundTab) {
      activeTab.value = foundTab.fullpath;
    } else {
      tabs.value.push({
        path: route.path,
        fullpath: route.fullPath,
        name: route.name as string,
        meta: route.meta,
        title:
          typeof route.query.title === "string"
            ? route.query.title
            : (route.meta?.title as string)
      });
      activeTab.value = route.fullPath;
    }
  },
  { immediate: true }
);

watch(
  () => activeTab.value,
  newPath => {
    router.push(newPath);
  }
);

const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: "remove" | "add"
) => {
  if (action === "remove") {
    let activeName = activeTab.value;
    if (activeName === targetName) {
      tabs.value.forEach((tab, index) => {
        if (tab.fullpath === targetName) {
          const nextTab = tabs.value[index + 1] || tabs.value[index - 1];
          if (nextTab) {
            activeName = nextTab.fullpath;
          }
        }
      });
    }
    activeTab.value = activeName;
    tabs.value = tabs.value.filter(tab => tab.fullpath !== targetName);
  }
};
</script>

<style>
.demo-tabs {
  position: relative;
  left: -20px;
  background-color: var(--practice-backgroud-color);
  width: calc(100% + 38px);
  padding-left: 20px;
  padding-right: 20px;
}

.demo-tabs > .el-tabs__content {
  padding: 0px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-tabs__header {
  padding: 0px;
  margin: 0px;
}
</style>
